package com.xyp.sso.realm;

import java.util.Collection;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xyp.sso.entity.Role;
import com.xyp.sso.entity.SSOShiroUser;

public class SSOAuthronizedRealm extends AuthorizingRealm {

    private static final Logger log = LoggerFactory.getLogger(SSOAuthronizedRealm.class);

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        log.info("doGetAuthorizationInfo:  principals=" + principals);
        final Collection<?> collection = principals.fromRealm(getName());
        if (collection.isEmpty()) return null;

        SSOShiroUser user = (SSOShiroUser) collection.iterator().next();

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        for (Role role : user.getRoles()) {
            info.addRole(role.getId() + "");
        }
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken token1 = (UsernamePasswordToken) token;

        String username = token1.getUsername();
        if ("admin".equals(username)) {
            SSOShiroUser user = SSOShiroUser.getDefaultShiroUser();

            return new SimpleAuthenticationInfo(user, "123456", getName());
        }

        return null;
    }

}
